package pers.course.test;

public class MyArrayList {
    private int size;
    private Object[] elements;

    public MyArrayList() {
        elements = new Object[10];
        size = 0;
    }

    public void add(Object o) {
        if (size >= elements.length) {
            Object[] newElements = new Object[size + 10];
            System.arraycopy(elements, 0, newElements, 0, size);
            elements = newElements;
        }
        elements[size] = o;
        ++size;
    }

    public Object get(int index) {
        if (index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        return elements[index];
    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        MyArrayList strList = new MyArrayList();
        strList.add("alpha");
        strList.add("beta");
        System.out.println(strList);
        for (int i = 0; i < strList.size; i++) {
            String str = (String) strList.get(i);
            System.out.println(str);
        }
//        strList.add(1234);
//        String str = (String) strList.get(2); // compile OK, runtime NOT OK
//        Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
//        at pers.course.test.MyArrayList.main(MyArrayList.java:43)
    }
}
